# 读取文件
import json
from pathlib import Path

path = Path("./files/pi_digits.txt")
contents = path.read_text()
print(contents)

###删掉read_text()最后返回的空字符串 即输出的空行
contents = contents.rstrip(contents)
print(contents)

### 链式调用 可以直接组合写
contents = path.read_text().rstrip()
print(contents)

##相对路径和绝对路径
path = Path("/Users/liuwei/PycharmProjects/pythonProject_liuwei/files/pi_digits.txt")
contents = path.read_text().rstrip()
print(contents)

## 访问文件中的各行
from pathlib import Path
path = Path("./files/pi_digits.txt")
contents = path.read_text()
lines = contents.splitlines()
print(type(lines))
print(lines)
for line in lines:
    print(line)

## 使用文件的内容
from pathlib import Path
path = Path("./files/pi_digits.txt")
contents = path.read_text()
lines = contents.splitlines()
pi_string = ""
for line in lines:
    pi_string += line.lstrip()

print("-------")
print(pi_string)
print(len(pi_string))

## 包含 100万位的大型文件
from pathlib import Path
path = Path("./files/pi_million_digits.txt")
contents = path.read_text() ## 只要内存够就能读进来
lines = contents.splitlines()
pi_string = ""
for line in lines:
    pi_string += line.lstrip()
print(type(pi_string))
print(f"{pi_string[:52]}...")
print(len(pi_string))

## 圆周率包含你的生日吗
from pathlib import Path
path = Path("./files/pi_million_digits.txt")
contents = path.read_text() ## 只要内存够就能读进来
lines = contents.splitlines()
pi_string = ""
for line in lines:
    pi_string += line
#birthday = input("Enter your birthday, in the form mmddyy:")
birthday = "111222"
if birthday in pi_string:
    print("YES")
else:
    print("NO")
print(type(contents))
print(contents[:50])

# 写入文件
## 写入一行 write_test()会创建文件、会删除文件中的内容再进行 write
from pathlib import Path
path = Path("./files/programming.txt")
path.write_text("I love programming.") ## python只能将字符串写入文本文档，如果有数值类型需要先使用 str()将其转换为字符串格式

## 写入多行
from pathlib import Path
contents = "I love programming2.\n"
contents += "I love creating new games.\n"
contents += "I also love working with data.\n"

path = Path("./files/programming.txt")
path.write_text(contents)

# 异常
## 处理ZeroDivisionError异常
#print(5/0)

##使用 try-except代码块
try:
    print(5/0)
except ZeroDivisionError:
    print("you can't divide by zero!")

## 简单计算器的例子
print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")

while True:
    first_number = input("\nFirst number:")
    if first_number == 'q':
        break
    second_number = input("\nFirst number:")
    if second_number == 'q':
        break
    try:
        answer = int(first_number) / int(second_number)
    except ZeroDivisionError:
        print("you can't devide by 0!")
    else:  # try执行成功后要执行的代码都放到 else 中
        print(answer)

## 处理 FileNotFoundError异常
from pathlib import Path
path = Path("./files/alice.txt")
try:
    contents = path.read_text()
except FileNotFoundError:
    print(f"Sorry,the file {path} does not exit.")

## 分析文本 #使用path()计算单词数
from pathlib import Path
path = Path("./files/alice.txt")
try:
    contents = path.read_text()
except FileNotFoundError:
    print(f"Sorry,the file {path} does not exist.")
else:
    # 计算大致包含多少单词
    words = contents.split()
    num_words = len(words)
    print(f"The file {path} has about {num_words} words.")

## 使用多个文件
from pathlib import Path
def count_words(path):
    """计算一个文件有多少单词"""
    try:
        contents = Path.read_text(path)
    except FileNotFoundError:
        print(f"Sorry,the file {path} does not exist.")
    else :
        word = contents.split()
        num_words = len(word)
        print(f"The file {path} has about {num_words} words.")
path = Path("./files/alice.txt")
count_words(path)
count_words(Path("./files/alice.txt"))

filenames = ["./files/alice.txt","./files/little_women.txt","./files/moby_dick.txt","./files/siddhartha.txt"]
for filename in filenames:
    path = Path(filename)
    count_words(Path(filename))
    count_words(path)

## 静默失败 使用 pass表示什么都不做
def count_words(path):
    """计算一个文件有多少单词"""
    try:
        contents = Path.read_text(path)
    except FileNotFoundError:
        pass
    else :
        word = contents.split()
        num_words = len(word)
        print(f"The file {path} has about {num_words} words.")
path = Path("./files/alice.txt")
count_words(path)
count_words(Path("./files/alice.txt"))

filenames = ["./files/alice.txt","./files/little_women.txt","./files/moby_dick.txt","./files/siddhartha.txt"]
for filename in filenames:
    path = Path(filename)
    count_words(Path(filename))
    count_words(path)

# 存储数据  #json
## 使用json.dumps() 存储    json.loads() 读取
"""json
只有数字、字符串、布尔
字符串必须是双引号
可以有数组使用[]
{
    "name" : "xx",
    "age" : 11,
    "hobby" : ["football","basketball"],
    "family" : "zhangsan"
}
"""
from pathlib import Path
import json
numbers = [2,3,5,7,11,13]
path = Path("./files/number.json")
contents = json.dumps(numbers)
path.write_text(contents)

contents2 = path.read_text()
numbers = json.loads(contents2)
print(numbers)
print(type(numbers))


## 保存和读取用户生成的数据
###保存
from pathlib import Path
import json
username = input("what is your name")
path = Path("./files/username.json")
contents = json.dumps(username)
path.write_text(contents)
print(f"we'll remember you when you come back, {username}!")

###读取
from pathlib import Path
import json
path = Path("./files/username.json")
contents = path.read_text()
username = json.loads(contents)
print(f"Welcome back, {username}!")

### 保存 + 读取
from pathlib import Path
import json
path = Path("./files/username.json")
if path.exists(): ##这里没有用 try-except 而是使用了 pathlib 中一个便利的方法
    contents = path.read_text()
    username = json.loads(contents)
    print(f"Welcome back,{username}!")
else :
    username = input("what is your name?")
    contents = json.dumps(username)
    path.write_text(contents)
    print(f"We'll remember you when you come back, {username}")

## 重构 让代码总结为函数
### 初步优化
from pathlib import Path
import json

def greet_user():
    """问候用户，并指出名字"""
    path = Path("./files/username3.json")
    if path.exists():
        contents = path.read_text()
        username = json.loads(contents)
        print(f"欢迎回来 {username}")
    else:
        username = input("请输入您的名字:")
        contents = json.dumps(username)
        path.write_text(contents)
        print(type(username))
        print(type(contents))
        print(f"我们将记得你，在你下次登录的时候 {username}")
        print(f"我们将记得你，在你下次登录的时候 {contents}")

greet_user()

### 最终优化
from pathlib import Path
import json

def get_stored_username(path):
    """如果存储了用户名就获取他"""
    if path.exists():
        contents = path.read_text()
        username = json.loads(contents)
        return username

def get_new_username(path):
    """提示用户输入用户名"""
    username = input("---请输入您的名字:")
    contents = json.dumps(username)
    path.write_text(contents)
    return  username

def greet_user():
    """问候用户，指出名字"""
    path = Path("./files/username4.json")
    username = get_stored_username(path)
    print("--- get_stored_username(path):{}".format(get_stored_username(path)))
    print("---username:%s %s" %(username,username))
    if username:
        print("---Welcom back,{}".format(username))
    else:
        username = get_new_username(path)
        print("we'll remember you when you come back,%s" %username)

greet_user()
